#include "msg_handler.h"
#include "data_global.h"

const s8 *u8NodeAddr[4] = {" ", "OM", "DATA", "RTE"};

/*****************************************************************
*   Function name:  OM_MSG_Creat
*   Description:    Message send
*   Input parameter:     
*   output parameter:  success : msgid  error :- 1
*****************************************************************/
MSG_Q_ID MSG_Creat()
{
	key_t key;
    MSG_Q_ID msgid;
    

    key = ftok("/", 1);
    msgid = msgget(key, IPC_CREAT|IPC_EXCL|0644);
    if(msgid < 0)
    {
        if(errno == EEXIST)
        {
            msgid = msgget(key,0644);
        }
        else
        {
            perror("msgget error");
           return -1;
        }
    }
	
	return msgid;

}

/*****************************************************************
*   Function name:  OM_MSG_Send
*   Description:    Message send
*   Input parameter:     msgid : the message queue identifier
*                       msgTxt : addr of the msg_send
*         You only need to fill: msgTxt->u16DstID; msgtxt.pu8Data
*   output parameter:  success : 0  error :- 1
*****************************************************************/

s32 MSG_Send(MSG_Q_ID msgid, STRU_MSG_HEADER *msgTxt)
{
    msgTxt->MsgType = (long)msgTxt->u16DstID;
    msgTxt->u16SrcID = NODE;

    if(msgsnd(msgid, (void *)msgTxt, MSG_LEN, 0) < 0)
    {
        perror("msgsnd err:");
        return -1;
    }
    return 0;
}
/*****************************************************************
*   Function name:  OM_MSG_Recv
*   Description:    Message recv
*   Input parameter:     msgid : the message queue identifier
*                       msgTxt : addr of the msg_recv
*   output parameter:  success : 0    error : -1
*****************************************************************/

s32 MSG_Recv(MSG_Q_ID msgid, STRU_MSG_HEADER *msgTxt)
{
    if(msgrcv(msgid, (void *)msgTxt, MSG_LEN, (long)NODE, 0) < 0)
    {
        perror("msgrcv err:");
        return -1;
    }
    return 0;
}
